# -*- coding: utf-8 -*-

from models.usuario import Usuario
from pages.basePage import BaseHandler
import jinja2
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
        
class Signup(BaseHandler):
    def get(self):
        userId = self.session.get('userid')
        user = None
        if userId is not None:
            user = Usuario.get_by_id(userId)
        if user is not None:
            self.redirect('/home')
            return
        template = jinja_environment.get_template('html/CadastrarUsuario.html')
        self.response.out.write(template.render())
        
    def post(self):
        login = self.request.get('username')
        password = self.request.get('password')
        password2 = self.request.get('password2')
        
        
        if login is None or login == '' or password is None or password == '' or password2 is None or password2 == '':
            # Campos obrigatórios
            self.redirect('/?erro=PreencherCampos')
            return            
        
        if password == password2:
            if (Usuario.exists(login)):
                # Login já cadastrado
                self.redirect('/?erro=LoginExistente')
                return            
            
            user = Usuario(email=login, senha=password)
            user.put()
            self.session['userid'] = user.key().id()
            self.redirect('/home')
        else:            
            # As senhas devem ser iguais
            self.redirect('/?erro=SenhasDiferentes')
        